const { Model, DataTypes } = require('sequelize');
const { sequelize } = require('../config/mysql_config');

class CoinLedger extends Model {}

CoinLedger.init(
    {
        id: { type: DataTypes.INTEGER.UNSIGNED, autoIncrement: true, primaryKey: true },
        accountType: {
            type: DataTypes.ENUM('user', 'advisor'),
            allowNull: false,
            comment: '账户类型',
        },
        accountId: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: false,
            comment: '用户ID或顾问ID',
        },
        orderId: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: true,
            comment: '关联订单',
        },
        commentId: {
            type: DataTypes.INTEGER.UNSIGNED,
            allowNull: true,
            comment: '评论ID'
        },
        bizType: {
            type: DataTypes.STRING(30),
            allowNull: false,
            comment: '业务类型',
        },
        amount: {
            type: DataTypes.INTEGER, // 金币可为负(出账)，无需 UNSIGNED
            allowNull: false,
            comment: '正数=入账 负数=出账(金币)',
        },
        balanceAfter: {
            type: DataTypes.INTEGER,
            allowNull: false,
            comment: '记账后余额(幂等对账)',
        }
    },
    {
        sequelize,
        modelName: 'CoinLedger',
        tableName: 'coin_ledger',
        underscored: true,
        timestamps: true,
        comment: '金币流水(统一账本)',
        indexes: [
            { name: 'idx_account_time', fields: ['account_type', 'account_id', 'created_at'] },
            { name: 'idx_order', fields: ['order_id'] },
        ],
    }
);

module.exports = CoinLedger;
